/**
 * Created by LeonTao on 17/2/13.
 */

/**
 * 请求地址：http://v.juhe.cn/weather/index
 请求参数：cityname=%E8%A5%BF%E5%AE%89&dtype=json&format=1&key=d89caf00c6d9f3ad680faba4057c7410
 请求方式：GET
 *
 */
//获取天气， 并且将数据存入数据库中

$(document).ready(function () {
    var cityname = '西安'

//定时执行获取天气的任务
    var weatherInterval = setInterval(getWeather(), 3600 * 24);

    function getWeather() {

        console.log("------------ getWeather ----------");
        var url = 'http://v.juhe.cn/weather/index';
        var para = {
            cityname: cityname || "西安",
            dtype: 'json',
            format: 1,
            key: 'd89caf00c6d9f3ad680faba4057c7410'
        };

        $.get(url, para, function (json) {
            if (Number(json.resultcode) === 200) { //成功
                var future = json.result.future;
                console.log("result: ", json.result);
                console.log("future: ", future);


                var weathers = [];
                var today = Number(moment().format("YYYYMMDD"));

                for (var i = 0; i < 5; i++) {
                    var day = today + i;
                    var index = 'day_' + day;

                    var dayWeather = future[index];

                    var weather = {
                        id: index,
                        day: day,
                        title: cityname + " " + dayWeather.weather + " " + dayWeather.temperature,
                        allDay: true,
                        start: day,
                        editable: false,
                        startEditable: false,
                        durationEditable: false,
                        color: '#EEEEEE',
                        backgroundColor: '#EEEEEE',
                        borderColor: '#EEEEEE',
                        textColor: '#646464'

                    };
                    weathers.push(weather);
                }
                // callback(weathers);
                //保存到数据库中
                store2DB(weathers);
            }
        });
    }

    function store2DB(weathers) {
        var weatherList = {'weatherList': weathers};
        $.post('/weathers-store', weatherList, function (result) {
            console.log("result: ", result);
        });
    }
});
